package com.koron.ticket.line.work.powerlinefirst.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.common.core.business.system.SystemCacheUtil;
import com.koron.ticket.feign.TicketChangeStatusFeign;
import com.koron.ticket.feign.bean.defectDispatch.DispatchVO;
import com.koron.ticket.feign.bean.defectDispatch.OrderDispatchWorker;
import com.koron.ticket.line.work.common.bean.FifteenTables;
import com.koron.ticket.line.work.common.bean.Print;
import com.koron.ticket.line.work.common.bean.SixteenTables;
import com.koron.ticket.line.work.common.service.FifteenTablesService;
import com.koron.ticket.line.work.common.service.SixteenTablesService;
import com.koron.ticket.line.work.enums.TicketNodeStatus;
import com.koron.ticket.line.work.enums.TicketStatus;
import com.koron.ticket.line.work.enums.TicketType;
import com.koron.ticket.line.work.enums.WorkFlowType;
import com.koron.ticket.line.work.workticket.bean.WorkTicket;
import com.koron.ticket.line.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.line.work.workticket.bean.po.LineTicketOrder;
import com.koron.ticket.line.work.workticket.service.LineTicketOrderService;
import com.koron.ticket.line.work.workticket.service.WorkTicketService;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workmember.bean.WorkMember;
import com.koron.ticket.work.workmember.service.WorkMemberService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@Service("linePowerLineFirstService")
public class PowerLineFirstService {

    @Autowired
    private SixteenTablesService lineSixteenTablesService;

    @Autowired
    private FifteenTablesService lineFifteenTablesService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkTicketService lineWorkTicketService;

    @Autowired
    private WorkMemberService workMemberService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkEndService workEndService;

    @Autowired
    private LineTicketOrderService lineTicketOrderService;

    @Autowired
    private TicketChangeStatusFeign ticketChangeStatusFeign;

    /**
     * 保存数据
     * 1. id为空是新增
     * 2. id不为空是更新
     *
     * @param factory
     * @param sixteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    @TaskAnnotation("writeSave")
    public Response writeSave(SessionFactory factory, SixteenTables sixteenTables) {
        // 1. 保存基本数据，并返回工作票id
        String workTicketId = lineSixteenTablesService.writeSave(factory, sixteenTables);
        workFlowService.deleteByWorkTicketId(factory, workTicketId, TicketStatus.WRITE.getStatus());
        // 2. 保存签名相关数据
        List<WorkFlow> workFlowList = sixteenTables.getWorkFlowList();
        workFlowList.stream().forEach(w -> {
            w.setWorkTicketId(workTicketId);
        });
        workFlowService.batchInsert(factory, workFlowList);

        // 3. 保存工单信息
        List<LineTicketOrder> lineTicketOrderList = sixteenTables.getLineTicketOrderList();
        lineTicketOrderList.forEach(e -> e.setWorkTicketId(workTicketId));
        lineTicketOrderService.removeByTicketId(factory, workTicketId);
        lineTicketOrderService.saveBatch(factory, lineTicketOrderList);
        return Response.success(workTicketId);
    }

    @TaskAnnotation("getPrintData")
    public List<Print> getPrintData(SessionFactory factory, String id) {
        List<Print> result = lineSixteenTablesService.getPrintData(factory, id);
        return result;
    }

    @TaskAnnotation("writeSubmit")
    public Response writeSubmit(SessionFactory factory, SixteenTables sixteenTables) {
        String workTicketId = lineSixteenTablesService.writeSubmitByWorkFlowType(factory, sixteenTables, WorkFlowType.LineFirst.getWorkFlow());
        return Response.success(workTicketId);
    }

    @TaskAnnotation("signSave")
    public Response signSave(SessionFactory factory, List<WorkFlow> workFlowList) {
        Optional<WorkFlow> first = workFlowList.stream().filter(w -> ObjectUtil.isNotNull(w.getUpdateTime())).findFirst();
        if (first.isPresent()) {
            WorkFlow workFlow = first.get();
            lineWorkTicketService.checkTimeOut(factory, workFlow.getWorkTicketId(), workFlow.getUpdateTime());//检查信息是否过期
        }
        for (WorkFlow workFlow : workFlowList) {
            if (StrUtil.isBlank(workFlow.getWorkTicketId())) {
                continue;
            }
            workFlowService.save(factory, workFlow);
        }
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("acceptSave")
    public Response acceptSave(SessionFactory factory, WorkFlow workFlow) {
        lineWorkTicketService.checkTimeOut(factory, workFlow.getWorkTicketId(), workFlow.getUpdateTime());//检查信息是否过期
        workFlowService.save(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("permitSave")
    public Response permitSave(SessionFactory factory, WorkPermit workPermit) {
        lineFifteenTablesService.permitSave(factory, workPermit);
        return Response.success("待许可-提交/保存成功");
    }

    @TaskAnnotation("workEndSave")
    public Response workEndSave(SessionFactory factory, WorkEnd workEnd) {
        lineFifteenTablesService.endSaveWithStatus(factory, workEnd, TicketStatus.WORK_END.getStatus());
        return Response.success("工作待终结-提交/保存成功");
    }

    @TaskAnnotation("ticketEndSave")
    public Response ticketEndSubmitOrSave(SessionFactory factory, WorkEnd workEnd) {
        lineFifteenTablesService.endSaveWithStatus(factory, workEnd, TicketStatus.TICKET_END.getStatus());
        return Response.success("工作票待终结-提交/保存成功");
    }

    @TaskAnnotation("workflowUpdate")
    public Response workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        Integer operation = redirectQuery.getOperation();
        String workTicketId = redirectQuery.getDataId();
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();
        String type = workTicket.getType();

        // 1. 如果被驳回，返回对应状态，仅删除签名的数据，其他的数据不做处理(没有会签阶段)
        if (operation == 1) {
            String rejectNodeCode = redirectQuery.getRejectNodeCode();
            rejectNodeCode = rejectNodeCode.replace("call-", "");
            if (rejectNodeCode.equals(TicketNodeStatus.WRITE.getNodeName())) {
                Integer rejectStatus = TicketStatus.WRITE.getStatus();
                // lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.SIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.SIGN.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.COUNTERSIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.COUNTERSIGN.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.ACCEPT.getNodeName())) {
                Integer rejectStatus = TicketStatus.ACCEPT.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.PERMIT.getNodeName())) {
                Integer rejectStatus = TicketStatus.PERMIT.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                // 20211111: 如何是待许可状态，讲预览标志设置成未预览
                workTicket.setPreviewFlag(1);
                workTicket.setStatus(rejectStatus);
            }  else if (rejectNodeCode.equals(TicketNodeStatus.EXECUTE.getNodeName())) {
                // 工作执行中状态
                Integer rejectStatus = TicketStatus.EXECUTE.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.WORK_END.getNodeName())) {
                Integer rejectStatus = TicketStatus.WORK_END.getStatus();
                lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
            }
            lineWorkTicketService.update(factory, workTicket);
        } // 2. 如果通过，工作票进入下一个状态，并根据状态的不同进行不同的操作
        else if (operation == 32) {
            String formVariables = redirectQuery.getFormVariables();
            // 2.1 如果是签发状态，1.保存签名信息；2.设置工作票号；3.跳过会签阶段
            if (status.equals(TicketStatus.SIGN.getStatus())) {
                // workFlowService.deleteByWorkTicketId(factory, workTicketId, TicketStatus.WRITE.getStatus());
                // 保存签名数据
                saveWorkFlow(factory, formVariables);
                // 设置工作票号
                if (StrUtil.isBlank(workTicket.getCode())) {
                    String code = lineFifteenTablesService.getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), type);
                    workTicket.setCode(code);
                }
            } else if (status.equals(TicketStatus.COUNTERSIGN.getStatus())) {
                // 保存签名数据   会签
//                saveWorkFlow(factory, formVariables);
                lineFifteenTablesService.saveWorkFLow(factory, formVariables);
            } // 2.3 如果是待接收状态：1.保存签名信息；2.将预览标志设为未预览
            else if (status.equals(TicketStatus.ACCEPT.getStatus())) {
                // 保存签名信息
                lineFifteenTablesService.saveWorkFLow(factory, formVariables);
                // 将预览标志设为未预览
                workTicket.setPreviewFlag(1);
            }
            // 2.4 如果是待许可状态，保存签名信息，以及待许可信息
            else if (status.equals(TicketStatus.PERMIT.getStatus())) {
                // 保存许可信息
                WorkPermit workPermit = JSONObject.parseObject(formVariables, WorkPermit.class);
                workPermit.setId(workPermit.getWorkPermitId());
                workPermit.setPermitTime(new Date());
                workPermitService.save(factory, workPermit);
                // 保存签名信息
                List<WorkFlow> workFlowList = workPermit.getWorkFlowList();
                if (workFlowList != null && workFlowList.size() > 0) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFlowService.save(factory, workFLow);
                    }
                }
                List<LineTicketOrder> lineTicketOrders = lineTicketOrderService.listByTicketId(factory, workTicket.getId());
                // 许可后变更工单状态为执行中
                EamUser redisUser = SystemCacheUtil.getRedisUser(workTicket.getDirector());
                List<WorkMember> workMembers = workMemberService.queryByWorkTicketId(factory, workTicketId);
                for (LineTicketOrder lineTicketOrder : lineTicketOrders) {
                    DispatchVO dispatchVO = new DispatchVO();
                    dispatchVO.setDefectId(lineTicketOrder.getOrderId());
                    dispatchVO.setLocation(workTicket.getLocation());
                    dispatchVO.setLocationName(workTicket.getLocationName());
                    dispatchVO.setNature(0);
                    dispatchVO.setStartTime(workTicket.getEstimatedStartTime());
                    dispatchVO.setEndTime(workTicket.getEstimatedEndTime());
                    dispatchVO.setOrderType("defect");
                    if (redisUser != null && Objects.equals("0", redisUser.getIsOutOrg())) {
                        dispatchVO.setLeader(workTicket.getDirector());
                        dispatchVO.setLeaderName(workTicket.getDirectorName());
                        dispatchVO.setIsOut(0);
                    } else {
                        dispatchVO.setIsOut(1);
                        for (WorkFlow workFlow : workFlowList) {
                            if (Objects.equals(workFlow.getType(), "wName")) {
                                dispatchVO.setLeaderName(workFlow.getAccount());
                                dispatchVO.setLeaderName(workFlow.getName());
                                break;
                            }
                        }
                        dispatchVO.setOutLeader(workTicket.getDirector());
                        dispatchVO.setOutLeaderName(workTicket.getDirectorName());
                    }
                    dispatchVO.setContext(workTicket.getContent());
                    if (redisUser != null) {
                        dispatchVO.setDeptWork(redisUser.getOrgId());
                        dispatchVO.setDeptWorkName(redisUser.getOrgName());
                    } else {
                        dispatchVO.setDeptWork(workTicket.getDeptId());
                        dispatchVO.setDeptWorkName(workTicket.getDeptName());
                    }
                    List<OrderDispatchWorker> list = new ArrayList<>();
                    dispatchVO.setOrderDispatchWorkerList(list);
                    for (WorkMember workMember : workMembers) {
                        OrderDispatchWorker orderDispatchWorker = new OrderDispatchWorker();
                        orderDispatchWorker.setWorker(workMember.getMemberAccount());
                        orderDispatchWorker.setWorkerName(workMember.getMemberName());
                        orderDispatchWorker.setJobDept(workMember.getMemberUnit());
                        orderDispatchWorker.setJobDeptName(workMember.getMemberUnitName());
                        // orderDispatchWorker.setType();
                        list.add(orderDispatchWorker);
                    }
                    // @TODO 应该是要设置成true的
                    // dispatchVO.setIsCommit(true);
                    ticketChangeStatusFeign.saveLineDispatchInfo(dispatchVO);
                    // ticketChangeStatusFeign.saveLineDispatchInfo(dispatchVO);
                }
            }
            // 2.4 如果是工作执行状态
            else if (status.equals(TicketStatus.EXECUTE.getStatus())) {
                // 不进行任何操作
                // lineOrderChangeStatusService.changeOrderStatus(workTicket.getOrderType(), workTicket.getOrderId());
            }
            // 2.5 如果是工作待终结保存签名信息，以及终结信息(工作票待终结直接调用workflowUpdateEnd接口)
            else if (status.equals(TicketStatus.WORK_END.getStatus())) {
                // 保存终结信息
                WorkEnd workEnd = JSONObject.parseObject(formVariables, WorkEnd.class);
                workEnd.setId(workEnd.getWorkEndId());
                workEndService.saveWithStatus(factory, workEnd, TicketStatus.WORK_END.getStatus());
                // 保存签名信息
                List<WorkFlow> workFlowList = workEnd.getWorkFlowList();
                if (workFlowList != null && workFlowList.size() > 0) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFlowService.save(factory, workFLow);
                    }
                }
                // 归档后，缺陷工单变为“待验收”
                List<LineTicketOrder> lineTicketOrders = lineTicketOrderService.listByTicketId(factory, workTicket.getId());
                for (LineTicketOrder lineTicketOrder : lineTicketOrders) {
                    if ("不维修".equals(lineTicketOrder.getStatus())) {
                        continue;
                    }
                    ticketChangeStatusFeign.submitLineDefect(lineTicketOrder.getOrderId(), "WAIT_ACCEPT");
                }

            }
            // 3. 状态更新，更新主票
            workTicket.setStatus(status + 1);
            lineWorkTicketService.update(factory, workTicket);
        } else if (operation == 256) {
            Integer rejectStatus = TicketStatus.WRITE.getStatus();
            lineFifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
            workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
            workTicket.setStatus(rejectStatus);
            lineWorkTicketService.update(factory, workTicket);
        } else {
            return Response.fail("操作类型为：" + operation + ",请联系运维人员");
        }

        return Response.success("机械工作票提交成功");
    }

    /**
     * 保存会签信息
     *
     * @param factory
     * @param formVariables
     */
    private void saveWorkFlow(SessionFactory factory, String formVariables) {
        WorkFlow workFlow = JSONObject.parseObject(formVariables, WorkFlow.class);
        String workFlowListString = workFlow.getWorkFlowListString();
        List list = JSONObject.parseObject(workFlowListString, List.class);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String json = JSONObject.toJSONString(list.get(i));
                lineFifteenTablesService.saveWorkFLow(factory, json);
            }
        }
    }

    @TaskAnnotation("workflowUpdateEnd")
    public Response workflowUpdateEnd(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        lineFifteenTablesService.workflowUpdateEnd(factory, redirectQuery);
        return Response.success("工作票已归档");
    }

    @TaskAnnotation("workflowUpdateCancel")
    public Response workflowUpdateCancel(SessionFactory factory, RedirectQuery redirectQuery) {
        lineFifteenTablesService.workflowUpdateCancel(factory, redirectQuery);
        return Response.success("工作票已作废");
    }

    public SixteenTables add() {
        SixteenTables sixteenTables = lineSixteenTablesService.addByType(TicketType.LineFirst.getType());
        return sixteenTables;
    }

    public SixteenTables getById(SessionFactory factory, String id) {
        SixteenTables sixteenTables = lineSixteenTablesService.getById(factory, id);
        // 查询工单信息
        List<LineTicketOrder> lineTicketOrders = lineTicketOrderService.listByTicketId(factory, id);
        sixteenTables.setLineTicketOrderList(lineTicketOrders);
        return sixteenTables;
    }

    public void deleteById(SessionFactory factory, String id) {
        lineSixteenTablesService.deleteById(factory, id);
    }
}
